import 'dart:async';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/utils.dart';

class BarChartSample extends StatefulWidget {
  final List data;

  BarChartSample({Key key, this.data}) : super(key: key);

  @override
  State<StatefulWidget> createState() => BarChartSampleState();
}

class BarChartSampleState extends State<BarChartSample> {
  List<BarChartGroupData> rawBarGroups;
  List<BarChartGroupData> showingBarGroups;
  StreamController<BarTouchResponse> barTouchedResultStreamController;
  int touchedGroupIndex;
  bool initSuccess = false;

  @override
  void initState() {
    super.initState();
  }

  Widget _buildLabel(title, color) {
    return Container(
      child: Row(
        children: <Widget>[
          Container(
            width: 36.w,
            height: 14.w,
            margin: EdgeInsets.only(right: 14.w),
            decoration: BoxDecoration(
              color: Utils.hexToColor(color),
              borderRadius: BorderRadius.circular(7.w)
            ),
          ),
          Text(title, style: TextStyle(
            color: Utils.hexToColor('#656565'),
            fontSize: 12
          ))
        ],
      ),
    );
  }

  stringToDouble(str) {
    return double.parse(str.toString());
  }

  initChart() {
    List<BarChartGroupData> items = [];

    if(widget.data != null) {
      for(var item in widget.data) {
        items.add(
          makeGroupData(2, 
            // stringToDouble(item['shelvesCount']), 
            stringToDouble(item['occupyCount'] == 0 ? 0.1 : item['occupyCount'])
          )
        );
      }

      rawBarGroups = items;
      showingBarGroups = rawBarGroups;

      barTouchedResultStreamController = StreamController();
      barTouchedResultStreamController.stream.distinct().listen((BarTouchResponse response) {
        if (response == null) {
          return;
        }

        if (response.spot == null) {
          setState(() {
            touchedGroupIndex = -1;
            showingBarGroups = List.of(rawBarGroups);
          });
          return;
        }

        touchedGroupIndex = showingBarGroups.indexOf(response.spot.touchedBarGroup);

        setState(() {
          if (response.touchInput is FlLongPressEnd) {
            touchedGroupIndex = -1;
            showingBarGroups = List.of(rawBarGroups);
          } else {
            showingBarGroups = List.of(rawBarGroups);
            if (touchedGroupIndex != -1) {
              double sum = 0;
              for (BarChartRodData rod in showingBarGroups[touchedGroupIndex].barRods) {
                sum += rod.y;
              }
              double avg = sum / showingBarGroups[touchedGroupIndex].barRods.length;

              showingBarGroups[touchedGroupIndex] = showingBarGroups[touchedGroupIndex].copyWith(
                barRods: showingBarGroups[touchedGroupIndex].barRods.map((rod) {
                  return rod.copyWith(y: avg);
                }).toList(),
              );
            }
          }
        });
      });
      
      setState(() {
        initSuccess = true;
      });
    }
  }


  lineBreak(str) {
    List arr = str.split('');
    List arr2 = [];

    for(var item in arr) {
      arr2.add(item+'\n');
    }
    return arr2.toString().replaceAll(',', '').replaceAll('[', '').replaceAll(']', '').replaceAll(' ', '');
  }

  Widget _buildChart() {
    if(initSuccess) {
      return FlChart(
        chart: BarChart(BarChartData(
          // maxY: 200,
          barTouchData: BarTouchData(
            touchTooltipData: TouchTooltipData(
              tooltipBgColor: Colors.grey,
              getTooltipItems: (spots) {
                return spots.map((TouchedSpot spot) {
                  return null;
                }).toList();
              }
            ),
            touchResponseSink: barTouchedResultStreamController.sink,
          ),
          gridData: FlGridData(
            show: true,
            drawHorizontalGrid: false,
            getDrawingVerticalGridLine: (value) {
              var number = value.toInt();
              
              if(number % 40 == 0) {
                return const FlLine(
                  color: Color(0xffF7F7F7),
                  strokeWidth:  1,
                );
              }else {
                return const FlLine(
                  color: Color(0xffffffff),
                  strokeWidth:  1,
                );
              }
            },
          ),
          titlesData: FlTitlesData(
            show: true,
            bottomTitles: SideTitles(
              showTitles: true,
              textStyle: TextStyle(
                color: const Color(0xff999999),
                fontSize: 9
              ),
              margin: 6,
              getTitles: (value) {
                String name = lineBreak(widget.data[value.toInt()]['name']);

                switch (value.toInt()) {
                  case 0:
                    return name;
                  case 1:
                    return name;
                  case 2:
                    return name;
                  case 3:
                    return name;
                  case 4:
                    return name;
                  case 5:
                    return name;
                  case 6:
                    return name;
                  case 7:
                    return name;
                  case 8:
                    return name;
                  case 9:
                    return name;
                  case 10:
                    return name;
                  case 11:
                    return name;
                  case 12:
                    return name;
                }
              },
            ),
            leftTitles: SideTitles(
              showTitles: true,
              textStyle: TextStyle(
                color: const Color(0xff999999),
                fontSize: 12
              ),
              margin: 20,
              reservedSize: 10,
              // getTitles: (value) {
              //   switch(value.toInt()) {
              //     case 0: return '0';
              //     case 40: return '40';
              //     case 80: return '80';
              //     case 120: return '120';
              //     case 160: return '160';
              //     case 200: return '200';
              //   }
              //   return '';
              // },
            ),
          ),
          borderData: FlBorderData(
            show: false,
            border: Border.all(color: Color(0xff37434d), width: 1)
          ),
          barGroups: showingBarGroups,
        )),
      );
    }else {
      return Container(child: Text(initSuccess.toString()),);
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    Timer(new Duration(milliseconds: 50), () {
      initChart();
    });

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      mainAxisAlignment: MainAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Expanded(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(15, 0, 25, 0),
            child: _buildChart()
          ),
        ),
        SizedBox(
          height: 70,
        ),
        Container(
          child: Align(
            child: Container(
              width: 347.w,
              margin: EdgeInsets.only(top: 10.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  // _buildLabel('总库位', '#F1F1F1'),
                  _buildLabel('已使用库位', '#297BFF'),
                ]
              )
            )
          )
        )
      ]
    );
  }

  BarChartGroupData makeGroupData(int x, double y2) {
    return BarChartGroupData(
      barsSpace: 0, 
      x: x, 
      barRods: [
        // BarChartRodData(
        //   y: y1,
        //   color: Color(0xffF2F2F2),
        //   width: 5,
        //   isRound: true,
        // ),
        BarChartRodData(
          y: y2,
          color: Color(0xff297CFF),
          width: 4,
          isRound: true,
        ),
      ]
    );
  }
}